package net.hserver.sync.service;

import cn.hserver.core.ioc.IocUtil;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.queue.HServerQueue;
import cn.hserver.core.task.TaskManager;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import net.hserver.sync.config.EventConst;
import net.hserver.sync.config.LogLevel;
import net.hserver.sync.config.LogType;
import net.hserver.sync.driver.WebDavDriver;
import net.hserver.sync.entity.SyncWebDavConfigEntity;
import net.hserver.sync.file.FileListener;
import net.hserver.sync.file.FileMonitor;
import net.hserver.sync.mapper.SyncWebDavConfigMapper;
import net.hserver.sync.task.TaskLocalRemote;
import net.hserver.sync.task.TaskRemoteLocal;

import java.util.Date;
import java.util.List;

@Bean
@Slf4j
public class SyncWebDavService {

    @Autowired
    private SyncWebDavConfigMapper syncWebDavConfigMapper;

    public boolean add(SyncWebDavConfigEntity webDavConfigEntity) {
        webDavConfigEntity.setId(null);
        webDavConfigEntity.setCreateTime(new Date());
        boolean b = syncWebDavConfigMapper.insert(webDavConfigEntity) > 0;
        addDriver(webDavConfigEntity);
        return b;
    }

    public List<SyncWebDavConfigEntity> list() {
        return syncWebDavConfigMapper.selectAll();
    }

    public boolean del(String id) {
        removeDriver(id);
        return syncWebDavConfigMapper.deleteById(id) > 0;
    }


    public void initDriver() {
        List<SyncWebDavConfigEntity> list = list();
        for (SyncWebDavConfigEntity syncWebDavConfigEntity : list) {
            addDriver(syncWebDavConfigEntity);
        }
    }

    public void addDriver(SyncWebDavConfigEntity syncWebDavConfigEntity) {
        //本地同步云端的同时是实时的才要添加监听
        if (syncWebDavConfigEntity.getSyncType() != SyncWebDavConfigEntity.SyncType.local_to_remote || StrUtil.isNotEmpty(syncWebDavConfigEntity.getSyncTime())) {
            if (syncWebDavConfigEntity.getSyncType() == SyncWebDavConfigEntity.SyncType.local_to_remote) {
                TaskManager.addTask(syncWebDavConfigEntity.getId(), syncWebDavConfigEntity.getSyncTime(), TaskLocalRemote.class, syncWebDavConfigEntity);
                log.info("添加本地同步云端定时监听：{}",syncWebDavConfigEntity.getId());
            } else {
                TaskManager.addTask(syncWebDavConfigEntity.getId(), syncWebDavConfigEntity.getSyncTime(), TaskRemoteLocal.class, syncWebDavConfigEntity);
                log.info("添加云端同步本地定时监听：{}",syncWebDavConfigEntity.getId());
            }
            IocUtil.addBean(syncWebDavConfigEntity.getId(), new WebDavDriver(
                    syncWebDavConfigEntity.getWebDavAddress(),
                    syncWebDavConfigEntity.getWebDavUsername(),
                    syncWebDavConfigEntity.getWebDavPassword(),
                    syncWebDavConfigEntity.getRemotePath(),
                    null

            ));
            return;
        }
        try {
            FileMonitor fileMonitor = new FileMonitor(1000);
            fileMonitor.monitor(new FileListener(syncWebDavConfigEntity));
            fileMonitor.start();
            IocUtil.addBean(syncWebDavConfigEntity.getId(), new WebDavDriver(
                    syncWebDavConfigEntity.getWebDavAddress(),
                    syncWebDavConfigEntity.getWebDavUsername(),
                    syncWebDavConfigEntity.getWebDavPassword(),
                    syncWebDavConfigEntity.getRemotePath(),
                    fileMonitor

            ));
            HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.OTHER, "添加了同步驱动：" + syncWebDavConfigEntity.getId());

        } catch (Exception e) {
            HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.SUCCESS, LogType.OTHER, "驱动初始化失败：" + syncWebDavConfigEntity.getId() + " 错误：" + e.getMessage());
            log.info("WebDavDriver init error:{}", e.getMessage());
        }
    }

    public void removeDriver(String id) {
        WebDavDriver bean = IocUtil.getBean(id, WebDavDriver.class);
        if (bean != null) {
            try {
                bean.getFileMonitor().stop();
            } catch (Exception e) {
                HServerQueue.sendQueue(EventConst.LOG_EVENT, LogLevel.ERROR, LogType.OTHER, "驱动删除失败：" + id + " 错误：" + e.getMessage());
                log.info("WebDavDriver stop error:{}", e.getMessage());
            }
        }
        TaskManager.removeTask(id);
        IocUtil.remove(id);
    }

}
